/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, useTheme, Table, TableBody, TableRow, Cell, CCell, Button, Collapse, TableHead
} from "customize-easy-ui-component";
import { DirectLink } from "../../../routing/Link";
import {CCellUnit, ReportViewProps,} from "../../common/base";
import {分项末尾链接, } from "../../common/rarelyVary";
import {useMainRepUrlOr, useSplitSubCapacity, useSplitSubRepList} from "../../hook/useMainRepUrlOr";
import HashLinkObserver from "react-hash-link";
import {config部位汇总, } from "./elvBase";
import RoutingContext from "../../../routing/RoutingContext";
import {useContext} from "react";

//正式报告的显示打印。 默认打印A4:210X297mm纸张。
//不需要每个verId新搞一个文件的，甚至不需要搞新的组件，可以只需内部逻辑处理。
//verId 实际在PeriodicalInspection.E配置文件中reportTemplate配上的。#不是路由器注入提供！！
//@param rep:主报告对象； 这个注入点：没有提供主报告id;需要从rep查找。【重要差别】独立流转的URL跳转后这里rep实际上是分项报告的并不是主报告的对象。
//【模板编码】分项报告的采取模板代码内置nestMd编码方案。主报告模板编码是rep?.注入的。
/**@param fxIdx: 独立流转模式的 分项序号的基数； 若是嵌入式的分项该参数=undefined! rep?.id!==repId
 * */
export const ReportView: React.FunctionComponent<ReportViewProps> = (
    {repId,   source: parentOrc,  verId,rep, redId,fxIdx ,...other}
) => {
    const theme= useTheme();
    const {urlMainRep}=useMainRepUrlOr(rep);
    const lsBlockMax=useSplitSubCapacity(parentOrc?._THICK_MS?.length,5);       //【模板敲定一次性最大几个分项显示出来】有些分项报告模板可能存在很多个分项 最多5个？
    const {sumArea, areaIdAs, btnBindUses}=useSplitSubRepList(parentOrc?._THICK_MS ?? [], lsBlockMax,false);
    const { get:getRouteUrl } = useContext(RoutingContext);
    const routeLevels=getRouteUrl().entries.length;
    const routeTemplate=getRouteUrl().entries[routeLevels-1]?.routeData?.params?.template;
    return (
     <React.Fragment>
      <HashLinkObserver />
      <div  id="rp_thickm_"  css={{
            "@media not print": {
                marginTop:'1rem',
                marginBottom: '1rem'
            },
      }}>
         <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/THICK_MS/_Controller`}>
            <div css={{"@media print":{display: 'none'} }}>
                <Button>{(repId===rep?.id && rep?.modeltype!=='THICK_MS')? '内嵌式的':'独立流转的'}壁厚测定报告分项控制器</Button>
            </div>
         </DirectLink>

        {(new Array(sumArea).fill(null)).map((s:any,ak:number) => {
            const [isDisplay, bindBtn]=btnBindUses[ak];      //不要加上 tabIndex={0} 超过折叠区域最大数量的？
            //可折叠区的：独立流转的报告，和内嵌分项的，实际还分开的。两者独自控制折叠的。内嵌分项rep.id相等，独立流转的却不等的ID;
            return <React.Fragment key={ak}>
                <div key={ak} role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                    { <Text variant="h4">{`壁厚折叠区${ak+1}，`}{isDisplay ? `收起`:`更多..`}</Text> }
                </div>
                <Collapse id={`${ak}`} show={isDisplay} noAnimated>
                    { areaIdAs[ak]?.map((surpId: any, m:number) => {
                        const orc=parentOrc['_THICK_MS_'+surpId];
                        const dispIdx=(fxIdx??0) +(m+ ak*lsBlockMax);
                        return <React.Fragment key={m}>
                            <div css={{marginTop: '1rem', "@media print": {pageBreakInside: 'avoid',} }}>
                                <Text variant="h3" css={{
                                    textAlign:'center',
                                    "@media (min-width:690px),print and (min-width:538px)": {
                                        fontSize: theme.fontSizes[6],
                                    }
                                }}>
                                    壁厚测定报告{dispIdx? '-'+dispIdx : ''}
                                </Text>
                                <div css={{
                                    display: 'flex',
                                    justifyContent: 'flex-end',
                                    flexDirection: 'row',
                                }}>
                                    <Text  css={{
                                        [theme.mediaQueries.md]: {
                                            marginRight: '2rem',
                                        }
                                    }}>
                                        报告编号：{rep.isp.no}
                                    </Text>
                                </div>
                                <Table  fixed={ ["17%","33%","17%","%"]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                                    <TableBody>
                                        <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Instrument`}>
                                            <TableRow>
                                                <CCell>设备名称</CCell>
                                                <CCell>{orc?.设备名称}</CCell>
                                                <CCell>设备编号</CCell>
                                                <CCell>{orc?.设备编号}</CCell>
                                            </TableRow>
                                        </DirectLink>
                                    </TableBody>
                                </Table>
                            </div>
                            <Table  fixed={ ["17%","33%","17%","%"]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                                <TableBody>
                                    <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Instrument`}>
                                        <TableRow>
                                            <CCell>仪器型号</CCell>
                                            <CCell>{orc?.仪器型号}</CCell>
                                            <CCell>仪器编号</CCell>
                                            <CCell>{orc?.仪器编号}</CCell>
                                        </TableRow>
                                        <TableRow>
                                            <CCell>仪器精度</CCell>
                                            <CCellUnit unit={'mm'}>{orc?.仪器精度}</CCellUnit>
                                            <CCell>耦合剂</CCell>
                                            <CCell>{orc?.耦合剂}</CCell>
                                        </TableRow>
                                    </DirectLink>
                                </TableBody>
                            </Table>
                            <Table  fixed={ ["17%","18%","12%","12%","16%","9%","%"]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                                <TableBody>
                                    <TableRow>
                                        {config部位汇总.map(([title,_2,_1], i:number) => {
                                            return <CCell key={i}>{title}</CCell>;
                                        }) }
                                    </TableRow>
                                    {/*分项模式的：就不能用href={`/report/THICK_MS/ver/${rep?.modelversion}/${rep?.id}/${surpId}/PartSummary#PartSummary`*/}
                                    <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/PartSummary#PartSummary`}>
                                        {(orc?.部位表??[{}])?.map((o: any, i:number) => {
                                            return (<TableRow key={i}>
                                                    <CCell>{o?.n}</CCell>
                                                    <CCell>{o?.c}</CCell>
                                                    <CCell>{o?.t}</CCell>
                                                    <CCell>{o?.f}</CCell>
                                                    <CCell>{o?.b}</CCell>
                                                    <CCell>{o?.d}</CCell>
                                                    <CCell>{o?.r}</CCell>
                                                </TableRow>
                                            );
                                        }) }
                                        <TableRow>
                                            <CCell>检测标准</CCell>
                                            { ak===0 && m===0?
                                                <Cell colSpan={6}>GB/T 11344-2021《无损检测 超声测厚》<br/>
                                                        NB/T 47013.3-2015 《承压设备无损检测 第3部份：超声检测》</Cell>
                                                :
                                                <CCell colSpan={6}>同上</CCell>
                                            }
                                        </TableRow>
                                    </DirectLink>
                                    <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Surface`}>
                                        <TableRow>
                                            <Cell colSpan={7} split={true} css={{"@media print": {height: undefined}, padding: 0}}>
                                                <div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                                                    <Text css={{fontSize: '0.8rem'}}>测厚点位置示图：</Text><br/>
                                                    {orc?.点图说明}
                                                </div>
                                                {orc?._FILE_S部位?.map(({name, url}: any, i: number) => {
                                                    return <div key={i} css={{"@media print": {pageBreakInside: 'avoid'}}}>
                                                        {i > 0 && <hr/>}
                                                        <div css={{contentVisibility: 'auto',display: 'flex', justifyContent: 'space-around', alignItems: 'center',}}>
                                                            {url &&
                                                                <img src={process.env.REACT_APP_OSS_ENDP + url} alt={url}
                                                                     css={{
                                                                         maxWidth: 'min(25cm, 100%)',
                                                                         "@media print": {maxHeight: '92vh', maxWidth: '100%'},
                                                                         //92vh=扣除掉适当的前抬头说明，页底部后人员行可能的空间。
                                                                     }}
                                                                />
                                                            }
                                                        </div>
                                                    </div>
                                                })}
                                            </Cell>
                                        </TableRow>
                                    </DirectLink>
                                      <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Measurement`}>
                                        <TableRow>
                                            <CCell colSpan={orc?.参见图? 2:7}>测 厚 记 录 （ 测点厚度单位：㎜）</CCell>
                                            {orc?.参见图 && <CCell colSpan={5}>{orc?.参见图}</CCell>}
                                        </TableRow>
                                     </DirectLink>
                                </TableBody>
                            </Table>
                            { orc?.测厚表?.length>0 &&
                                <Table  fixed={ ["8.7%","7.96%","8.7%","7.96%","8.7%","7.96%","8.7%","7.96%","8.7%","7.96%","8.7%","%"]  } css={ {borderCollapse: 'collapse' } }
                                        tight  miniw={800}>
                                    <TableHead>
                                        <TableRow>
                                            {(new Array(6).fill(null)).map((a:any,i:number) => {
                                                return (
                                                    <React.Fragment key={i}><CCell>测点编号</CCell><CCell>测点厚度</CCell></React.Fragment>
                                                );
                                            } )  }
                                        </TableRow>
                                    </TableHead>
                                    <TableBody>
                                        <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Measurement`}>
                                            {orc?.测厚表?.map((o: any, i: number) => {
                                                return (
                                                    <TableRow key={i}>
                                                        <CCell>{o.no1}</CCell>
                                                        <CCell>{o.vl1}</CCell>
                                                        <CCell>{o.no2}</CCell>
                                                        <CCell>{o.vl2}</CCell>
                                                        <CCell>{o.no3}</CCell>
                                                        <CCell>{o.vl3}</CCell>
                                                        <CCell>{o.no4}</CCell>
                                                        <CCell>{o.vl4}</CCell>
                                                        <CCell>{o.no5}</CCell>
                                                        <CCell>{o.vl5}</CCell>
                                                        <CCell>{o.no6}</CCell>
                                                        <CCell>{o.vl6}</CCell>
                                                    </TableRow>
                                                );
                                            } )
                                            }
                                        </DirectLink>
                                    </TableBody>
                                </Table>
                            }
                            <Table fixed={ ["62%","%"]  }  css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                                <TableBody>
                                    { orc?.记录备注 &&
                                        <DirectLink  href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Instrument#Instrument`}>
                                            <TableRow>
                                                <Cell component="th" scope="row" colSpan={2}>
                                                    <div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                                                        <Text css={{fontSize: '0.8rem'}}>备注：</Text><br/>
                                                        {orc?.记录备注 || '／'}
                                                 </div></Cell>
                                            </TableRow>
                                        </DirectLink>
                                    }
                                    <DirectLink href={`/report/THICK_MS/ver/${verId}/${repId}/${surpId}/Surface`}>
                                    <TableRow>
                                            <Cell split={true} colSpan={2}><div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                                                <Text css={{fontSize:'0.8rem'}}>检测结果：</Text><br/>
                                                {orc?.检测结果 || '／'}
                                            </div></Cell>
                                        </TableRow>
                                    </DirectLink>
                                    <TableRow>
                                        <CCell><div css={{height: '100%',display: 'flex',justifyContent: 'space-between',alignContent: 'space-between',alignItems: 'flex-start'}}>
                                            <div><Text>检验：</Text>    </div>
                                            <div css={{textAlign: 'end'}}><Text >日期</Text>2022-12-31</div>
                                        </div></CCell>
                                        <CCell><div css={{height: '100%',display: 'flex',justifyContent: 'space-between',alignContent: 'space-between',alignItems: 'flex-start'}}>
                                            <div><Text >审核：</Text>  </div>
                                            <div css={{textAlign: 'end'}}><Text >日期</Text>2021-01-31</div>
                                        </div></CCell>
                                    </TableRow>
                                </TableBody>
                            </Table>

                        </React.Fragment>;
                    }) }

                    <div role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                        <Text variant="h4">{`壁厚折叠区${ak+1}结束,收起`}</Text>
                    </div>
                </Collapse>

            </React.Fragment>
        })}

      </div>
       {分项末尾链接({template:'THICK_MS', repId: repId||'',verId,urlMainRep,
           nestIn:'THICK_MS'!==routeTemplate, flowNest: repId!==rep?.id}) }
     </React.Fragment>
    );
}

//旧版的：会导致hash路由定位有问题的版本。 怪啊：旧版的Hash定位还和浏览器相关：Chrome电脑开发者模式不行， 手机横板状态也不行。
// {orc?._FILE_S部位?.map(({name, url}: any, i: number) => {
//     return <div key={i} css={{"@media print": {pageBreakInside: 'avoid'}}}>
//         {i > 0 && <hr/>}
//         <div css={{display: 'flex', justifyContent: 'space-around', alignItems: 'center',}}>
//             {url &&
//                 <img src={process.env.REACT_APP_OSS_ENDP + url} alt={url}
//                      css={{
//                          maxHeight: '14cm',   //在这个元素的上一级元素可以自己加一个固定高度值，就像一张纸打印的应该多高的取值。这个用固定高度会导致图片自动的横竖比例不均衡压缩=会变形啊！24cm是纸张大约最多高度=报告最大图片高。
//                          maxWidth: '-webkit-fill-available',
//                          [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},           //普通图片+大屏幕限制高度才是关键的。
//                          "@media print": {maxHeight: '86vh', maxWidth: '100%'},        //对A4纸张竖版的高度26cm基本都是图片整张纸，这里没考虑多个图片在宽度方向上的并排布局：可用软件合并。
//                      }}
//                 />
//             }
//         </div>
//     </div>
// })}
//开发模式的disable cache 再加载img导致; 最终依赖 contentVisibility: 'auto', 解决。
//解决Hash定位不准确的新版本如下： {orc?._FILE_S部位?.map( {          } )}
